package com.zx.mes.hyl.weather.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zx.mes.feign.hyl.feign.RedisWeatherClient;
import com.zx.mes.hyl.weather.entity.WeatherResponse;

import com.zx.mes.hyl.weather.service.WeatherDataServiceI;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;

/**
 * 实现WeatherDataServiceI接口
 * @author hyl
 * @date 2018-3-1
 */
@Service
public class WeatherDataServiceImpl implements WeatherDataServiceI{

    private static final String URL = "https://www.sojson.com/open/api/weather/json.shtml?city=";
     private static final int HTTP_STATUS_INT = 200;
    public static final String HYL = "hyl";

    private static final Logger logger = LoggerFactory.getLogger(WeatherDataServiceImpl.class);


    private RestTemplate restTemplate=new RestTemplate();

    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    @Autowired
    private RedisWeatherClient redisWeatherClient;

    @Override
    public WeatherResponse getDataByCityName(String cityName) {
        WeatherResponse resp = null;
        ObjectMapper mapper = new ObjectMapper();

        String cacheStr=redisWeatherClient.getWeatherCache(URL + cityName);
        logger.info("不管有无缓存,先从缓存中尝试获取:"+cacheStr);
        //没有找到缓存

        if (HYL.equals(cacheStr)) {
            ResponseEntity<String> respString = restTemplate.getForEntity(URL+cityName, String.class);

            String strBody ;
            if (respString.getStatusCodeValue() == HTTP_STATUS_INT) {
                strBody = respString.getBody();
                try {
                    resp=mapper.readValue(strBody, WeatherResponse.class);
                    logger.info("向redis中写入缓存!");
                    redisWeatherClient.setWeatherCache(URL + cityName, strBody);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } else {
            try {
                resp=mapper.readValue(cacheStr, WeatherResponse.class);
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return resp;
    }
}
